package com.interviewbackend.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

@Component
public class InterviewEvaluationClient {

    @Value("${qwen.api.key}")
    private String apiKey;

    @Value("${qwen.api.url}")
    private String apiUrl;

    @Value("${qwen.model.name}")
    private String modelName;

    private OpenAIClient client;

    @PostConstruct
    public void init() {
        client = OpenAIOkHttpClient.builder()
                .apiKey(apiKey)
                .baseUrl(apiUrl)
                .build();
    }

    public String evaluateOverall(String prompt) {
        try {
            Object raw = client.chat().completions().create(ChatCompletionCreateParams.builder()
                    .model(modelName)
                    .addUserMessage(prompt)
                    .build());

            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> resultMap = mapper.convertValue(raw, Map.class);
            List<Map<String, Object>> choices = (List<Map<String, Object>>) resultMap.get("choices");

            if (choices != null && !choices.isEmpty()) {
                Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
                if (message != null && message.get("content") != null) {
                    return message.get("content").toString().trim();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "【生成评估报告失败，请稍后再试】";
    }

}
